﻿//alert("horray!!!");

//Need ajax
var ajax = function (method, url, data, success, error) {
    var request = new XMLHttpRequest();
    request.open(method, url, false);
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            success(JSON.parse(this.response));
        } else {
            console.log("Error on " + method);
            error();
        }
    };
    request.onerror = function () {
        console.log("Communication error");
        error();
    }
    if (data) {
        request.send(JSON.stringify(data));
    } else {
        request.send();
    }
}
//Need draw table

//Need add todo

//Need delete

//Need update


var moveToBottom = true;

var Task = function (task) {
    this.Task = task;
    this.TimeStamp = Date.now();
    this.IsFinished = false;
};

var taskArray = [];

var addTask = function () {
    //adding task to db
    var newTask = new Task(document.getElementById("enteredTask").value);
    ajax("POST", "/api/values/", newTask, function (data) {
        taskArray.push(data);
    })
    document.getElementById("enteredTask").value = "";
    //print to screen
    writeTasks();
};
document.getElementById("addTaskButton").onclick = addTask;

var getAllTasks = function () {
    ajax("GET", "/api/values/", null, function (data) {
        taskArray = [];
        for (var i in data.ToDoList) {
            var t = data.ToDoList[i];
            taskArray.push(t);
        }
        writeTasks();
    })
};

var writeTasks = function () {
    //document.getElementById("addItems").innerHTML = "";
    document.getElementById("taskTable").innerHTML = "";

    for (var i in taskArray) {
        var tableRow = document.createElement("tr");
        var tdCheck = document.createElement("td");
        var tdTask = document.createElement("td");
        var tdTimeStamp = document.createElement("td");
        var tdButtons = document.createElement("td")

        //var deleteButton = document.createElement("button");
        var editButton = document.createElement("button");

        var checkBox = document.createElement("input");
        var table = document.getElementById("taskTable");

        //editButton.addEventListener("onclick", function () { alert(taskArray[i].Id); });

        checkBox.setAttribute("type", "checkbox");
        checkBox.setAttribute("onclick", "setCheck(" + taskArray[i].Id + ")");
        if (taskArray[i].IsFinished) {
            tableRow.setAttribute("style", "background-color:red");
        }

        if (taskArray[i].editing) {
            var textBox = document.createElement("input");
            textBox.setAttribute("type", "text");
            textBox.setAttribute("id", "edit-task");
            textBox.setAttribute("value", taskArray[i].Task);

            tdTask.appendChild(textBox);

            editButton.setAttribute("onclick", "saveTask(" + taskArray[i].Id + ")");
            editButton.setAttribute("class", "btn btn-success btn-sm");
            editButton.innerHTML = "Save";
        } else {
            editButton.setAttribute("onclick", "editTask(" + taskArray[i].Id + ")");
            editButton.setAttribute("class", "btn btn-warning btn-sm");
            editButton.innerHTML = "Edit";

            tdTask.innerHTML = taskArray[i].Task;
        }


        //tdTimeStamp.innerHTML = taskArray[i].TimeStamp;
        tdTimeStamp.innerHTML = Date(taskArray[i].TimeStamp).toString();

        if (taskArray[i].IsFinished) {
            checkBox.checked = true;

        }

        tdCheck.appendChild(checkBox);
        tdButtons.appendChild(editButton);



        tableRow.appendChild(tdCheck);
        tableRow.appendChild(tdTask);
        tableRow.appendChild(tdTimeStamp);
        tableRow.appendChild(tdButtons);

        table.appendChild(tableRow);


        //if (taskArray[i].IsFinished == true) {
        //    document.getElementById("addItems").innerHTML += "<li class='list-group-item col-xs-12 listDoneTrue'><input type='checkbox' checked class='checkbox col-xs-1' onchange='finishedTask("+(taskArray[i].Id)+");'><span class='col-xs-8'>"+taskArray[i].Task+"</span><span class='col-xs-2'>"+taskArray[i].TimeStamp+"</span></li></div>";
        //} else {
        //    document.getElementById("addItems").innerHTML += "<li class='list-group-item col-xs-12 listDoneFalse'><input type='checkbox' class='checkbox col-xs-1'onchange='finishedTask(" + (taskArray[i].Id) + ");'><span class='col-xs-8'>" + taskArray[i].Task + "</span><span class='col-xs-2'>" + taskArray[i].TimeStamp + "</li></div>";
        //}
    }
};

var editTask = function (taskId) {
    var task;
    for (var i in taskArray) {
        delete taskArray[i].editing;
        if (taskArray[i].Id == taskId) {
            task = taskArray[i];
        }
    }

    task.editing = true;

    writeTasks();
}

var saveTask = function (taskId)
{
    var taskText = document.getElementById("edit-task");
    var task;
    for (var i in taskArray) {
        if (taskArray[i].Id == taskId) {
            task = taskArray[i];
            break;
        }
    }

    task.Task = taskText.value;

    ajax("PUT", "/api/values/", task, function (data) {
        getAllTasks();
    })

   
}

var finishedTask = function (i) {
    //strikethrough or change color of finished task
    taskArray[i].isDone = !taskArray[i].isDone;
    taskArray[i].markFinished();
    writeTasks();
};

var setCheck = function (id) {
    for (var i in taskArray) {
        if (taskArray[i].Id === id)
        {
            taskArray[i].IsFinished = !taskArray[i].IsFinished;
            ajax("PUT", "/api/values/" + taskArray[i].Id, null, function () { });
            break;
        }
    }
    writeTasks();
}

var clearCheckedElements = function () {
    for (var i in taskArray) {
        if (taskArray[i].IsFinished === true) {
            ajax("DELETE", "/api/values/" + taskArray[i].Id, null, function () { });
        }
    }
                getAllTasks();
    
};
document.getElementById("clearFinished").onclick = clearCheckedElements;

var moveCheckedToBottom = function () {
    var lastIndex = taskArray.length;
    var temp;
    if (moveToBottom) {
        for (var i = taskArray.length - 1; i >= 0; i--) {
            if (taskArray[i].isDone) {
                taskArray.push(taskArray.splice(i, 1).pop());
            }
        }
        document.getElementById("moveFinishedToBot").innerHTML = "Move finished to top";
    }
    else {
        for (var i = 0; i < lastIndex; i++) {
            if (taskArray[i].isDone) {
                taskArray.unshift(taskArray.splice(i, 1).pop());
            }
        }
        document.getElementById("moveFinishedToBot").innerHTML = "Move finished to bottom";
    }
    moveToBottom = !moveToBottom

    writeTasks();
};
getAllTasks();